package com.labichaoka.chaoka.utils;

import android.content.Context;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;

import java.lang.ref.WeakReference;

/**
 * Author:zarle.
 * Created on 17-5-16.
 * SMSManager manage global send VerifyCode state
 */

public class SMSManager {

    private static SMSManager instance;

    private Context mContext;

    private WeakReference<TextView> bindView;


    private CountDownTimer mCountDownTimer = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            if (bindView == null)
                return;
            TextView view = bindView.get();
            if (view != null) {
                view.setClickable(false);// 设置不能点击
                Spannable span = new SpannableString(millisUntilFinished / 1000 + "秒后可重发");// 获取按钮的文字
                span.setSpan(new ForegroundColorSpan(Color.RED), 0, 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);//
                // 讲倒计时时间显示为红色
                view.setText(span);
            }
        }

        @Override
        public void onFinish() {
            if (bindView == null)
                return;
            TextView view = bindView.get();
            if (view != null) {
                view.setText("重新发送");
                view.setClickable(true);
            }
        }
    };

    public static SMSManager getInstance(Context appContext) {
        if (instance == null)
            instance = new SMSManager(appContext);
        return instance;
    }

    private SMSManager(Context context) {
        mContext = context.getApplicationContext();
    }


    public void bindView(TextView bindView) {
        this.bindView = new WeakReference(bindView);
    }

    public void start() {
        mCountDownTimer.start();

    }

    public void cancel(){
        mCountDownTimer.cancel();
    }


}
